package com.chzc.fm.duotin.ui.mine.utils;

import android.content.Context;
import android.content.Intent;

import com.chzc.fm.duotin.bean.mine.FileInfo;
import com.chzc.fm.duotin.bean.mine.ThreadInfo;
import com.chzc.fm.duotin.db.ThreadDAO;
import com.chzc.fm.duotin.db.ThreadDAOImpl;
import com.chzc.fm.duotin.event.DownloadEvent;
import com.chzc.fm.duotin.ui.mine.service.DownloadService;
import com.chzc.fm.duotin.utils.FileUtils;
import com.chzc.fm.duotin.utils.LogUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 下载任务类
 * Created by BillSinla on 2016/7/4.
 */
public class DownloadTask {

    private Context context = null;
    private FileInfo fileInfo = null;
    private ThreadDAO threadDao = null;

    //定义结束点
    private long finished;

    //第一次初始化自动进入
    private boolean initFlag = true;

    //队列存放FileInfo
    private Queue<FileInfo> fileInfoQueue;

    //是否暂停
    public boolean isPause = false;

    //线程
    public DownLoadThread downLoadThread = null;

    //下载更新事件
    private DownloadEvent event = null;

    //更新的进度
    private int progress = 0;

    public DownloadTask(Context context) {
        this.context = context;
        threadDao = new ThreadDAOImpl(context);
        fileInfoQueue = new LinkedList<FileInfo>();
        event = new DownloadEvent();
    }

    //添加新的文件下载
    public void addFileInfo(FileInfo fileInfo){
        fileInfoQueue.add(fileInfo);

        //发送文件的更新信息
        event.setState(DownloadEvent.UPDATE_FILE);
        event.setFileInfoQueue(fileInfoQueue);
        EventBus.getDefault().post(event);

        //当线程是空的时候，是否是第一次进入，是否暂停
        if(downLoadThread == null || initFlag){
            this.fileInfo = fileInfoQueue.peek();
            initFlag = false;
            download();
        }
    }

    //移除下载的文件
    public void removeFileInfo(){
        //删除线程信息
        threadDao.deleteThread(fileInfo.getUrl(), fileInfo.getId());

        fileInfoQueue.remove();
        downLoadThread = null;

        if(fileInfoQueue.size() == 0){
            event.setState(DownloadEvent.NONE);
            event.setFileInfoQueue(fileInfoQueue);
        }else{
            event.setState(DownloadEvent.UPDATE_FILE);
            event.setFileInfoQueue(fileInfoQueue);
        }
        EventBus.getDefault().post(event);
        if(fileInfoQueue.size() > 0){
            this.fileInfo = fileInfoQueue.peek();
            download();
        }
    }

    public void continueDownload(){
        isPause = false;
        download();
    }


    public Queue<FileInfo> getFileInfoQueue() {
        return fileInfoQueue;
    }

    public void download(){
        List<ThreadInfo> threadInfoList = threadDao.getThreads(fileInfo.getUrl());
        LogUtil.w("thread size = " + threadInfoList.size());
        ThreadInfo info;
        if(threadInfoList.size() == 0){
            info = new ThreadInfo(0, fileInfo.getUrl(), 0, fileInfo.getLength(), 0);
        }else{
            info = threadInfoList.get(0);
        }
        event.setFileInfoQueue(fileInfoQueue);
        event.setState(DownloadEvent.PREPARE);
        event.setProgress(0);
        downLoadThread = new DownLoadThread(info);
        downLoadThread.start();
    }

    class  DownLoadThread extends Thread{
        private ThreadInfo threadInfo = null;

        public DownLoadThread(ThreadInfo threadInfo){
            this.threadInfo = threadInfo;
        }

        @Override
        public void run() {
            //如果指定目录不存在，那么创建所有层级目录
            if(!FileUtils.DIR_MP3.exists()){
                FileUtils.DIR_MP3.mkdirs();
            }
            //设置文件写入位置
            File file = new File(FileUtils.DIR_MP3, FileUtils.getFileNameByHashCode(fileInfo.getFileName()));

            //向数据库插入线程信息
            if(!threadDao.isExists(threadInfo.getUrl(), threadInfo.getId())){
                threadDao.insertThread(threadInfo);
            }
            HttpURLConnection conn = null;
            RandomAccessFile raf = null;
            InputStream input = null;
            try{
                URL url = new URL(threadInfo.getUrl());
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(3000);
                conn.setRequestMethod("GET");
                //设置下载位置
                long start = threadInfo.getStart() + threadInfo.getFinished();
                conn.setRequestProperty("Range", "bytes=" + start + "-" + threadInfo.getEnd());


                raf = new RandomAccessFile(file, "rwd");
                raf.seek(start);

                Intent intent = new Intent(DownloadService.ACTION_UPDATE);
                finished = threadInfo.getFinished();
                //开始下载
                if(conn.getResponseCode() == HttpURLConnection.HTTP_PARTIAL){
                    //读取数据
                    input = conn.getInputStream();
                    byte[] buffer = new byte[1024 * 4];
                    int len = 1;
                    long time = System.currentTimeMillis();
                    while ((len = input.read(buffer)) != -1){
                        //下载暂停时，保存进度
                        if(isPause){
                            LogUtil.w("Size =" + fileInfo.getLength() + "Finished" + finished);
                            fileInfo.setFinished(finished);
                            threadDao.updateThread(fileInfo.getUrl(), 0, fileInfo.getFinished());

                            //发送暂停信息
//                            event.setState(DownloadEvent.PAUSE);
//                            EventBus.getDefault().post(event);
                            return;
                        }

                        //写入文件
                        raf.write(buffer, 0, len);
                        //把下载进度广播给Activity
                        finished += len;
                        if(System.currentTimeMillis() - time >= 1000){  //减少UI压力
                            time = System.currentTimeMillis();

                            progress = (int)(finished * 100 / fileInfo.getLength());
                            intent.putExtra("finished", (int)(finished * 100 / fileInfo.getLength()));
                            context.sendBroadcast(intent);

                            //发送更新信息
//                            event.setState(DownloadEvent.UPDATE);
//                            event.setProgress(progress);
//                            EventBus.getDefault().post(event);
                            LogUtil.w("finished :" + finished * 100 / fileInfo.getLength());
                        }
                    }
                    //发送下载完成信息
//                    event.setState(DownloadEvent.UPDATE);
//                    event.setProgress(100);

//                    EventBus.getDefault().post(event);
                    intent.putExtra("finished", 100);
                    context.sendBroadcast(intent);
                    LogUtil.w("finished :" + 100);
                    //删除线程并且开始新的下载
                    removeFileInfo();
                }

            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    if (conn != null && raf != null && input != null) {
                        input.close();
                        raf.close();
                        conn.disconnect();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
